import { StyleSheet, Text, View, ScrollView, TouchableOpacity } from 'react-native';
import React, { useState, useRef, useEffect } from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import { useNavigation, useRoute } from '@react-navigation/native';
import Video from 'react-native-video';
import { useTranslation } from 'react-i18next';
import { useAddMessage } from '~/common';
import { NavBarHeader, ContentStatus, UpoadAudioMode, MyLoading } from '~/components';
import { px2dp, scale } from '~/utils/px2dp';
import { leaveMessageList } from '~/api/leaveMessage';
import { addLeaveMessageApi } from '~/api/doctor';

export default function DoctorVoiceList() {
    const navigation = useNavigation();
    const router: any = useRoute();
    const { t } = useTranslation();
    const { device_sn, user_id = '', actionType = '' } = router.params || {};
    const [listData, setListData] = useState([]);
    const [visible, setVisible] = useState(false);
    const { addMessage, loading, error } = useAddMessage();
    const loadingRef = useRef<any>();
    const getData = () => {
        leaveMessageList({ device_sn }).then((res) => {
            const { data, code } = res;
            if (code !== 200) return;
            setListData(data);
        });
    };
    useEffect(() => {
        getData();
    }, []);
    const addMess = async () => {
        loadingRef.current.showLoading();
        try {
            const response = await addMessage({
                type: 5,
                title: t('doctor.t44'),
                content: t('doctor.t45'),
                user_id: user_id,
            });
            loadingRef.current.hideLoading();
            if (response.message == 'ok') {
                Toast.show({ content: t('doctor.t9'), layout: 'top' });
            } else {
                Toast.show({ content: response.message, layout: 'top' });
            }
        } catch (err) {
            loadingRef.current.hideLoading();
        }
    };
    const audioConfirm = (res) => {
        loadingRef.current.showLoading();
        addLeaveMessageApi({
            device_sn,
            audio_url: res.audio_url,
            audio_id: res.audio_id,
            duration: res.duration,
        })
            .then((res) => {
                loadingRef.current.hideLoading();
                if (res.status == 1) {
                    Toast.show({ content: t('doctor.t28'), layout: 'top' });
                    if (actionType == 'doctor') {
                        addMess();
                    }
                    navigation.goBack();
                } else {
                    Toast.show({ content: res.msg, layout: 'top' });
                }
            })
            .catch((err) => {
                loadingRef.current.hideLoading();
            });
    };
    const [currentAudioUrl, setCurrentAudioUrl] = useState<string | null>(null);
    const videoRef = useRef<any | null>(null);
    const [isPlaying, srtIsPlaying] = useState(false);
    const [selectIndex, setSelectIndex] = useState(-1);
    const handleAudioPress = (url: string) => {
        if (currentAudioUrl === url) {
            // 点击的是当前播放的音频，则暂停
            setCurrentAudioUrl(null);
            srtIsPlaying(false);
        } else {
            // 先暂停当前播放的音频，然后播放新音频
            setCurrentAudioUrl(url);
            srtIsPlaying(true);
        }
    };
    return (
        <View style={styles.container}>
            <NavBarHeader
                title={t('doctor.t30')}
                rightComponent={
                    <TouchableOpacity onPress={() => setVisible(true)}>
                        <Text style={styles.rightText}>{t('doctor.t31')}</Text>
                    </TouchableOpacity>
                }
            />
            <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.contentContainerStyle}>
                {listData?.length > 0 ? (
                    <View>
                        {listData?.map((item: any, index) => {
                            return (
                                <TouchableOpacity
                                    key={parseInt(item.id)}
                                    style={[styles.taskCard]}
                                    onPress={() => {
                                        handleAudioPress(item.audio_url);
                                        setSelectIndex(index);
                                    }}>
                                    <View style={[styles.row, styles.listHeader]}>
                                        <Text style={styles.t2} numberOfLines={1} ellipsizeMode="tail">
                                            {t('doctor.t32')}
                                            {index + 1}
                                        </Text>
                                        <Icon
                                            name={isPlaying && selectIndex == index ? 'pause' : 'play-circle'}
                                            size={24}
                                            color="#111111"></Icon>
                                    </View>
                                    <Text style={styles.add_time}>
                                        {t('doctor.t33')}：{item.add_time}
                                    </Text>
                                </TouchableOpacity>
                            );
                        })}
                    </View>
                ) : (
                    <ContentStatus status="empty" />
                )}
            </ScrollView>
            <UpoadAudioMode visible={visible} onCancel={() => setVisible(false)} onConfrim={audioConfirm} />
            {currentAudioUrl && (
                <Video
                    ref={(ref) => (videoRef.current = ref)}
                    source={{ uri: currentAudioUrl }}
                    resizeMode="cover"
                    paused={!currentAudioUrl} // 只有当 `currentAudioUrl` 不为空时才播放
                    onEnd={() => setCurrentAudioUrl(null)} // 结束后自动清除播放状态
                />
            )}
            <MyLoading ref={loadingRef} />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    contentContainerStyle: {
        flexGrow: 1,
        paddingBottom: '20%',
    },
    taskCard: {
        backgroundColor: '#FFF',
        marginTop: px2dp(32),
        padding: px2dp(24),
        borderRadius: px2dp(16),
        marginHorizontal: px2dp(24),
    },
    listHeader: {
        justifyContent: 'space-between',
    },
    t2: {
        fontSize: scale(30),
        fontWeight: 'bold',
        color: '#191919',
        marginTop: px2dp(12),
        lineHeight: px2dp(40),
    },
    t1: {
        fontSize: scale(24),
        fontWeight: 'bold',
        marginTop: px2dp(20),
    },
    add_time: {
        color: '#a4a4a4',
        fontSize: scale(24),
        marginTop: px2dp(20),
    },
    rightText: {
        marginRight: px2dp(32),
        color: '#111111',
        fontSize: scale(28),
    },
});
